package com.easylinkin.linkappapi.powerdistribution.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.easylinkin.linkappapi.powerdistribution.entity.*;
import com.easylinkin.linkappapi.powerdistribution.mapper.CompanyManageMapper;
import com.easylinkin.linkappapi.powerdistribution.mapper.DistributionCabinetMapper;
import com.easylinkin.linkappapi.powerdistribution.mapper.DistributionRoomMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.space.entity.LinkappArea;
import com.easylinkin.linkappapi.space.vo.SpaceTreeVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;
import java.util.stream.Collectors;

import com.easylinkin.linkappapi.powerdistribution.mapper.DistributionCabinetArchivesMapper;
import com.easylinkin.linkappapi.powerdistribution.service.DistributionCabinetArchivesService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;

@Service
public class DistributionCabinetArchivesServiceImpl extends ServiceImpl<DistributionCabinetArchivesMapper, DistributionCabinetArchives> implements DistributionCabinetArchivesService {
    @Resource
    LinkappUserContextProducer linkappUserContextProducer;
    @Resource
    CompanyManageMapper companyManageMapper;
    @Resource
    DistributionRoomMapper distributionRoomMapper;
    @Resource
    DistributionCabinetMapper distributionCabinetMapper;

    /***
     * 查询区域树
     * @param distributionAreaParam
     * @return
     */
    @Override
    public List<SpaceTreeVo> selectLinkappAreaTreeList(DistributionAreaParam distributionAreaParam) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //获取公司列表
        List<CompanyManageBean> companyManageBeans = new LambdaQueryChainWrapper<>(companyManageMapper)
                .select(CompanyManageBean::getId, CompanyManageBean::getCompanyName)
                .eq(CompanyManageBean::getTenantId, tenantId)
                .list();
        if (companyManageBeans == null || companyManageBeans.size() <= 0) {
            return null;
        }
        //获取公司ID
        Set<Integer> companyIds = companyManageBeans.stream().map(CompanyManageBean::getId).collect(Collectors.toSet());
        //查询站点
        List<DistributionRoom> distributionRooms = new LambdaQueryChainWrapper<>(distributionRoomMapper)
                .select(DistributionRoom::getId, DistributionRoom::getName,DistributionRoom::getCompanyInfoId)
                .eq(DistributionRoom::getTenantId, tenantId)
                .in(DistributionRoom::getCompanyInfoId, companyIds)
                .list();
        if(distributionRooms == null || distributionRooms.size()<=0){
            //提前返回
            return getSpaceTreeVoList(companyManageBeans,distributionRooms,null);
        }
        //获取配电柜
        Set<String> roomIds = distributionRooms.stream().map(DistributionRoom::getId).collect(Collectors.toSet());
        DistributionCabinet distributionCabinet = new DistributionCabinet();
        distributionCabinet.setTenantId(tenantId);
        distributionCabinet.setRoomIds(roomIds);
        List<DistributionCabinet> cabinetList=distributionCabinetMapper.getDistributionCabinetByAttr(distributionCabinet,distributionAreaParam.getFieldProperties());
        //参数组装
        return getSpaceTreeVoList(companyManageBeans,distributionRooms,cabinetList);
    }

    /***
     * 修改档案信息
     * @param distributionCabinetArchives
     */
    @Override
    public void saveOrUpdateEntity(DistributionCabinetArchives distributionCabinetArchives){
        if(distributionCabinetArchives == null){
            return;
        }
        Assert.notNull(distributionCabinetArchives.getCabinetId(),"cabinetId 不能为空" );
        Integer count = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(DistributionCabinetArchives::getCabinetId, distributionCabinetArchives.getCabinetId())
                .count();
        if(count == null || count <=0){
            save(distributionCabinetArchives);
        }else{
            new LambdaUpdateChainWrapper<>(baseMapper)
                    .set(DistributionCabinetArchives::getManufacturer, distributionCabinetArchives.getManufacturer())
                    .set(DistributionCabinetArchives::getDom, distributionCabinetArchives.getDom())
                    .set(DistributionCabinetArchives::getRatedCapacity, distributionCabinetArchives.getRatedCapacity())
                    .set(DistributionCabinetArchives::getRatedVoltage, distributionCabinetArchives.getRatedVoltage())
                    .set(DistributionCabinetArchives::getAddress, distributionCabinetArchives.getAddress())
                    .set(DistributionCabinetArchives::getRemarks, distributionCabinetArchives.getRemarks())
                    .eq(DistributionCabinetArchives::getCabinetId, distributionCabinetArchives.getCabinetId())
                    .update();
        }
    }

    /***
     * 查询设备档案
     * @param distributionCabinetArchives
     * @return
     */
    @Override
    public DistributionCabinetArchivesVo getDistributionCabinetArchives(DistributionCabinetArchives distributionCabinetArchives){
        Assert.notNull(distributionCabinetArchives, "参数不能为空");
        Assert.notNull(distributionCabinetArchives.getCabinetId(),"cabinetId 不能为空" );
        //效验
        Integer count = new LambdaQueryChainWrapper<>(distributionCabinetMapper)
                .eq(DistributionCabinet::getId, distributionCabinetArchives.getCabinetId())
                .count();
        if(count == null || count <=0){
            throw new IllegalArgumentException("cabinetId 不存在");
        }
       return baseMapper.getDistributionCabinetArchives(distributionCabinetArchives);
    }



    /***
     * 将公司、站点、配电柜组装为区域返回
     * @param companyManageBeans 公司集合
     * @param distributionRooms 站点集合
     * @param cabinetList  配电柜集合
     * @return
     */
    private List<SpaceTreeVo> getSpaceTreeVoList(List<CompanyManageBean> companyManageBeans, List<DistributionRoom> distributionRooms, List<DistributionCabinet> cabinetList) {
        if (companyManageBeans == null || companyManageBeans.size() <= 0) {
            return null;
        }
        ArrayList<SpaceTreeVo> spaceTreeVos = new ArrayList<>();
        //声明站点map
        Map<Integer, List<DistributionRoom>> companyInfoIdMap = null;
        if (distributionRooms != null && distributionRooms.size() > 0) {
            companyInfoIdMap = distributionRooms.stream().collect(Collectors.groupingBy(DistributionRoom::getCompanyInfoId, Collectors.toList()));
        }
        //声明配电柜map
        Map<String, List<DistributionCabinet>> distributionRoomIdMap = null;
        if (cabinetList != null && cabinetList.size() > 0) {
            distributionRoomIdMap = cabinetList.stream().collect(Collectors.groupingBy(DistributionCabinet::getDistributionRoomId, Collectors.toList()));
        }
        //添加公司
        String space = "space",area="area",cabi="cabinet";
        Map<Integer, List<DistributionRoom>> finalCompanyInfoIdMap = companyInfoIdMap;
        Map<String, List<DistributionCabinet>> finalDistributionRoomIdMap = distributionRoomIdMap;
        companyManageBeans.stream().forEach(m->{
            //添加空间
            SpaceTreeVo spaceTreeVo = new SpaceTreeVo();
            spaceTreeVo.setId(m.getId() + "");
            spaceTreeVo.setName(m.getCompanyName());
            spaceTreeVo.setAreaPath(m.getCompanyName());
            spaceTreeVo.setLevel(0);
            spaceTreeVo.setNodeType(space);
            spaceTreeVos.add(spaceTreeVo);

            //添加区域
            if(finalCompanyInfoIdMap == null ||  finalCompanyInfoIdMap.get(m.getId()) == null){
                return;
            }
            List<DistributionRoom> rooms = finalCompanyInfoIdMap.get(m.getId());
            rooms.stream().forEach(room->{
                SpaceTreeVo areaTreeVo = new SpaceTreeVo();
                areaTreeVo.setId(room.getId());
                areaTreeVo.setName(room.getName());
                areaTreeVo.setAreaPath(m.getCompanyName()+":"+room.getName());
                areaTreeVo.setParentId(m.getId()+"");
                areaTreeVo.setLevel(spaceTreeVo.getLevel()+1);
                areaTreeVo.setNodeType(area);
                spaceTreeVos.add(areaTreeVo);

                //添加三级区域
                if(finalDistributionRoomIdMap == null || finalDistributionRoomIdMap.get(room.getId()) == null){
                    return;
                }
                List<DistributionCabinet> distributionCabinets = finalDistributionRoomIdMap.get(room.getId());
                distributionCabinets.stream().forEach(cabinet->{
                    SpaceTreeVo childSpaceTreeVo = new SpaceTreeVo();
                    childSpaceTreeVo.setId(cabinet.getId());
                    childSpaceTreeVo.setName(cabinet.getName());
                    childSpaceTreeVo.setAreaPath(m.getCompanyName()+":"+room.getName()+":"+cabinet.getName());
                    childSpaceTreeVo.setParentId(room.getId()+"");
                    childSpaceTreeVo.setLevel(areaTreeVo.getLevel()+1);
                    childSpaceTreeVo.setNodeType(cabi);
                    spaceTreeVos.add(childSpaceTreeVo);
                });
            });
        });
        return spaceTreeVos;
    }
}

